package com.mxchip.livestar.ui.dial

import android.content.Intent
import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.umeng.analytics.MobclickAgent
import com.mxchip.livestar.CallActivityA
import com.mxchip.livestar.R
import com.mxchip.livestar.base.CallLogViewModel
import com.mxchip.livestar.utils.MyLog
import com.mxchip.livestar.rx.RxSchedulersHelper
import com.mxchip.livestar.rest.log.RetrofitFactory
import com.mxchip.livestar.base.SystemData
import com.mxchip.livestar.base.toast
import com.mxchip.livestar.ui.GroupCall
import com.mxchip.livestar.ui.P2PSingleCall
import kotlinx.android.synthetic.main.fragment_dial.*
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * 拨号界面
 */
class DialFragment : Fragment() {

    private val dialViewModel by viewModels<DialViewModel>()
    private val callLogViewModel by viewModels<CallLogViewModel>()

    private var music = 0
    private val sp: SoundPool by lazy {
        val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build()

        SoundPool.Builder()
                .setMaxStreams(10)
                .setAudioAttributes(audioAttributes)
                .build()
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_dial, container, false)

        MobclickAgent.onPageStart("DialFragment")

        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
        //把你的声音素材放到res/raw里，第2个参数即为资源文件，第3个为音乐的优先级
        music = sp.load(context, R.raw.play, 1)

        dialViewModel.setMyNumber(SystemData.userId())

        dialViewModel.number.observe(viewLifecycleOwner, Observer {
            text_dial_number.text = it
        })

        dialViewModel.myNumber.observe(viewLifecycleOwner, Observer { myNumber ->

            if (myNumber.isNullOrBlank()) {
                return@Observer
            }

            val myShortNumber = myNumber.trimStart('0')
            text_local_number_code.text = getString(R.string.local_number_str) + myShortNumber
        })

        text_local_number_code.setOnClickListener {
            val number = text_dial_number.text.toString()
            val rootPath = Environment.getExternalStorageDirectory().absolutePath + File.separator
            var relativePath = "Android/data/com.videohigh.hxb3288a/files/duobeiyun_paas/"
            val path = rootPath + relativePath
            when (number) {
                UPLOAD_FILES_TEXT -> {
                    uploadFiles("microlog.txt")
                }
                UPLOAD_TODAY_DBY_LOG_TEXT -> {
                    uploadTodayLog(path, relativePath)
                }
                UPLOAD_YESTERDAY_DBY_LOG_TEXT -> {
                    uploadLastLog(path, relativePath)
                }
                TEST_TEXT -> {
                    MyLog.logD(MyLog.DIAL_FRAGMENT_MODEL,"DialFragment::" + "onResume: clickTest")
                    test()
                }
            }
        }

        arrayOf(
                dial_item_1, dial_item_2, dial_item_3,
                dial_item_4, dial_item_5, dial_item_6,
                dial_item_7, dial_item_8, dial_item_9,
                dial_item_l, dial_item_0, dial_item_r
        ).forEach {
            it.setOnClickListener { view ->
                if (!SystemData.globalIsAuth) return@setOnClickListener
                sp.play(music, 1f, 1f, 0, 0, 1f)
                (view.tag as String?)?.let { digit ->
                    dialViewModel.appendDigit(digit)
                }
            }
        }

        item_delete.setOnLongClickListener {
            sp.play(music, 1f, 1f, 0, 0, 1f)
            dialViewModel.clearAllDigits()
            true
        }

        item_delete.setOnClickListener {
            sp.play(music, 1f, 1f, 0, 0, 1f)
            dialViewModel.removeLastDigit()
        }

        item_call.setOnClickListener {
            try {
                val call = dialViewModel.makeCall()
                val callString = when (call) {
                    is P2PSingleCall ->
                        call.number
                    is GroupCall ->
                        call.groupNumber

                    else ->
                        throw IllegalStateException("call is Unknow type")
                }
                callLogViewModel.createCallLog(callString, "2")

                context?.let { CallActivityA.open(it, call) }
            } catch (t: Throwable) {
                t.message?.let { toast(it) }
            }
        }

    }

    private fun uploadTodayLog(path: String, relativePath: String) {
        val today: String = getToday() //当前时间
        if (!File("$path$today.txt").exists()) {
            uploadLastLog(path, relativePath)
            return
        }
        uploadFiles("$relativePath$today.txt", true)
    }

    private fun uploadLastLog(path: String, relativePath: String) {
        var lastTimeLog = lastTimeLog(path)
        if (lastTimeLog == null) {
            toast("无最近7日使用记录")
        } else {
            toast("最近一次使用的日期为:$lastTimeLog")
            uploadFiles("$relativePath$lastTimeLog.txt", true)
        }
    }

    private fun lastTimeLog(path: String): String? {
        var loopCount = 0
        var yesterdayDate = getYesterday(Date())
        var yesterday: String? = SimpleDateFormat("yyyy_MM_dd").format(yesterdayDate)
        while (!File("$path$yesterday.txt").exists()) {
            MyLog.logD(MyLog.DIAL_FRAGMENT_MODEL,"DialFragment::lastTimeLog: $path$yesterday.txt ")
            if (loopCount > 7) {
                yesterday = null
                break
            }
            yesterdayDate = getYesterday(yesterdayDate)
            yesterday = SimpleDateFormat("yyyy_MM_dd").format(yesterdayDate)
            loopCount++
        }
        return yesterday
    }

    private fun getToday(): String {
        val sdf = SimpleDateFormat("yyyy_MM_dd")
        val today: String = sdf.format(Date()) //当前时间
        return today
    }

    private fun getYesterday(date: Date): Date {
//        val today = Date()
        //用当天的日期减去昨天的日期
        //用当天的日期减去昨天的日期
        return Date(date.time - 86400000L)
    }

    private fun test() {
        /*val testBody = TestBody()
        testBody.str1 = "test1"
        testBody.str2 = "test2"
        testBody.str3 = "test3"
        testBody.str4 = "test44"
        Appli.getSocketClient().newTest(testBody) { ack: Array<Any> -> MyLog.logD("DialFragment::" + "test:----------- " + ack[ack.size - 1].toString()) }*/

        /*Appli.getSocketClient().videoDeviceOpen("aaa", "bbb") {
            MyLog.logD("DialFragment::videoDeviceOpen:----------- $it")
        }

        Appli.getSocketClient().videoDeviceClose("ddd", "ccc") {
            MyLog.logD("DialFragment::videoDeviceClose:----------- $it")
        }*/


        /*val testBody = TestBody()
        testBody.str1 = "test1"
        testBody.str2 = "test2"
        testBody.str3 = "test3"
        testBody.str4 = "test44"

        RoomClientRepository.test(testBody)*/
        var intent = Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);

    }

    private fun uploadFiles(fileName: String, isPass: Boolean = false) {
        lifecycleScope.launch {
            MyLog.logD(MyLog.DIAL_FRAGMENT_MODEL,"DialFragment::uploadFiles:  ")
            RetrofitFactory.updateFile(fileName, isPass).compose(RxSchedulersHelper.io()).subscribe({ baseBean ->
                Log.d(TAG, baseBean.toString())
            }, { error ->
                Log.e(TAG, error.toString())
            })
            toast("日志文件上传成功")
        }


    }

    override fun onDestroy() {
        MobclickAgent.onPageEnd("DialFragment")
        sp.release()
        super.onDestroy()
    }

    companion object {
        private const val TAG = "DialFragment"
        private const val UPLOAD_FILES_TEXT = "4848#*#*"

        //传递今日的pass日志
        private const val UPLOAD_TODAY_DBY_LOG_TEXT = "4949#*#*"

        //传递昨日的pass日志
        private const val UPLOAD_YESTERDAY_DBY_LOG_TEXT = "4948#*#*"

        private const val TEST_TEXT = "4848*#*#"
    }
}

data class TestBody(
        var str1: String? = null,
        var str2: String? = null,
        var str3: String? = null,
        var str4: String? = null
)